#ifndef MODBUSHANDLER_H
#define MODBUSHANDLER_H

#include <QObject>
#include <QSerialPort>
#include "qdatetime.h"
class ModbusHandler : public QObject
{
    Q_OBJECT

public:
    explicit ModbusHandler(QObject *parent = nullptr);
    void connectToPort(const QString &portName);
    void readAllRegisters();
    void setBaudRate(int rate);
    void disconnectPort();
    bool isPortOpen() const;
    void calculateEnergy(double current);
    void clearEnergy();
    void saveEnergyData();      // 保存电量数据
    void loadEnergyData();      // 读取电量数据
signals:
    void dataRead(double voltage, double current, int soc, int soh,
                  double temperatures[6], double cellVoltages[16],
                  quint16 protectionFlags1, quint16 protectionFlags2,
                  double ratedCapacity,int cellCount,int cycleCount);
    void energyUpdated(double chargeAh, double dischargeAh);
    void dataCollected(const QString &timestamp,double voltage, double current, int soc, int soh,
                       double temperatures[6], double cellVoltages[16],
                       quint16 protectionFlags1, quint16 protectionFlags2,
                       double ratedCapacity,int cellCount,int cycleCount);

private slots:
    void handleReadyRead();
    void handleTimeout();


private:
    quint16 calculateCRC(const QByteArray &data);
    QSerialPort serial;
    QByteArray responseBuffer;
    int baudRate = 115200;
    double totalChargeAh = 0.0;  // 充电总量
    double totalDischargeAh = 0.0;  // 放电总量
    QDateTime lastUpdateTime;  // 上次更新时间

};

#endif // MODBUSHANDLER_H
